import bluetooth
from bluetooth import BLE
from bluetooth import UUID
import ustruct
import utime as time
from micropython import const

_ble_rx = None
_connect = 0

#adv
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)

_FLAG_READ = const(0x0002)
_FLAG_WRITE = const(0x0008)
_FLAG_NOTIFY = const(0x0010)

_ADV_TYPE_FLAGS = const(0x01)
_ADV_TYPE_NAME = const(0x09)
_ADV_TYPE_UUID16_COMPLETE = const(0x3)
_ADV_TYPE_UUID32_COMPLETE = const(0x5)
_ADV_TYPE_UUID128_COMPLETE = const(0x7)
_ADV_TYPE_APPEARANCE = const(0x19)

#从机UUID,UUID必须是128位字节,即16进制32位.
_UART_UUID = bluetooth.UUID("211e1c1a-1816-1412-0f0d-0b0907050301")
_UART_TX = (
    bluetooth.UUID("211e1c1a-1816-1412-0f0d-0b0907050302"),
    _FLAG_READ | _FLAG_WRITE ,
)
_UART_RX = (
    bluetooth.UUID("211e1c1a-1816-1412-0f0d-0b0907050303"),
    _FLAG_READ | _FLAG_NOTIFY,
)

_UART_SERVICE = (
    _UART_UUID,
    (_UART_TX, _UART_RX),
)

class BLESimplePeripheral:
############################################################################################
    def __init__(self, ble):      #从机设备名称,更改名字便于寻找
############################################################################################
        self._ble = ble
        self._ble.active(True)
        time.sleep_ms(2000)
    
        #通过config更改配置时，一定要先设置mode为空闲状态，否则mac更改不成功，name在广播数据中还是默认值
        self._ble.config(mode="I",gap_name="hello123",advint=2,power=2,mac="12345678aabb",mode="B")
        time.sleep_ms(200)
        print((self._ble.config("mac")))
        print(self._ble.config("mode"))
        print(self._ble.config("civer"))
        print(self._ble.config("advint"))
        print(self._ble.config("power"))
        print(self._ble.config("gap_name"))
        self._ble.irq(self._irq)

    def _irq(self, event, data):
        # Track connections so we can send notifications.
        if event == _IRQ_CENTRAL_CONNECT:
            print('connect')
            global _connect
            _connect = 1
        elif event == _IRQ_CENTRAL_DISCONNECT:
            print('disconnect')
            global _connect
            _connect = 0 
        elif event == _IRQ_GATTS_WRITE:
            buffer = self._ble.gatts_read(_ble_rx)
            print('recv data:',buffer)


    def send(self, data):
        self._ble.gatts_write(0, data)

    def is_connected(self):
        return len(self._connections) > 0

    def on_write(self, callback):
        self._write_callback = callback

def demo():
    time.sleep(5)
    ble = bluetooth.BLE()
    p = BLESimplePeripheral(ble)

    while True:
        if _connect == 1:
            p.send('data')
        time.sleep_ms(1000)
        

if __name__ == "__main__":
    demo()

